<template>
  <ContentWrap>
    <div style="display: flex; justify-content: center">
      <el-input
        v-model="queryParams.searchText"
        minlength="4"
        maxlength="200"
        :clearable="true"
        class="mr-3"
        show-word-limit
        style="width: 600px"
        @keyup.enter="getList"
      />

      <el-button @click="handleClickSearch" v-hasPermi="['customer:customerDuplicateCheck:list']">
        <Icon icon="ep:search" />
        查重
      </el-button>

      <el-button @click="handleClickMerge" v-hasPermi="['customer:customerDuplicateCheck:merge']">
        合并用户
      </el-button>
      <el-button
        @click="handleClickSetting"
        v-hasPermi="['customer:customerDuplicateCheck:setting']"
      >
        查重设置
      </el-button>
    </div>
    <div style="display: flex; justify-content: center" class="mt-2">
      <el-checkbox v-model="queryParams.isMailSuffix" class="!mr-2" />
      <el-text>按邮箱查询时，同时查询邮箱后缀相同的客户（不含平台邮箱，如gmail.com） </el-text>
    </div>
  </ContentWrap>
  <ContentWrap>
    <Table ref="tableRef" :columns="columns" :adaptive="true" :data="queryData" height-per="90" />
  </ContentWrap>
  <CustomerDuplicateCheckSetting ref="settingRef" @success="getDuplicateSetting" />
  <CustomerMerge ref="mergeRef" @success="handleClickSearch" />
</template>
<script setup name="CustomerDuplicateCheck" lang="ts">
import CustomerDuplicateCheckSetting from './CustomerDuplicateCheckSetting.vue'
import CustomerMerge from './CustomerMerge.vue'
import * as CustomerCheckApi from '@/api/customer/customerCheck'
import Highlight from '@/components/Highlight/src/Highlight.vue'
import { upperFirst } from 'lodash-es'
import { getKeyList } from '@pureadmin/utils'

import { SettingBusinessModuleEnum } from '@/utils/constants'
import { getBussinessModule } from '@/views/setting/businessField/BusinessFieldUtil'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

const message = useMessage() // 消息弹窗
const recycleMessage = ref('回收站')
const settingRef = ref()
const mergeRef = ref()
const settingColumnNames = ref()

const queryParams = ref({
  searchText: '',
  isMailSuffix: true
})
const queryData = ref()
const socialMediaType = ref()
const tableRef = ref()

let columns = ref<any[]>([
  {
    label: '客户编号',
    prop: 'customerNo',
    minWidth: '140'
  }
])

/** 初始化 */
onMounted(() => {
  dataInit()
})

function createHighlightRender(fieldName) {
  return ({ row }) =>
    h(
      Highlight,
      {
        backgroundColor: 'yellow',
        color: 'black',
        keys: [queryParams.value.searchText]
      },
      () => row[fieldName]
    )
}

const dataInit = async () => {
  columns.value = [
    {
      type: 'selection',
      alignWhole: 'center'
    },
    {
      label: '客户编号',
      prop: 'customerNo',
      minWidth: '140'
    },
    {
      label: '名称',
      prop: 'name',
      cellRenderer: createHighlightRender('name')
    },
    {
      label: '简称',
      prop: 'shortName',
      cellRenderer: createHighlightRender('shortName')
    },
    {
      label: '所属人',
      prop: 'owner.nickname'
    },

    {
      label: '所属部门',
      prop: 'dept.name'
    },

    {
      label: '网址',
      prop: 'showWebsite',
      cellRenderer: createHighlightRender('showWebsite')
    },
    {
      label: '国家',
      prop: 'country.name'
    }
  ]
  await getDuplicateSetting()
  socialMediaType.value = await getIntDictOptions(DICT_TYPE.COMMON_SOCIAL_MEDIA_TYPE)
  // 加载业务字段
  const customerModuleField = await getBussinessModule(SettingBusinessModuleEnum.CUSTOMER)

  customerModuleField.immutableFields.forEach((item) => {
    columns.value.push({
      label: item.showName,
      prop: item.fieldName,
      formatter: (row) =>
        row[item.fieldName] == 0
          ? ''
          : item.options.find((obj) => obj.id === row[item.fieldName])?.name
    })
  })
  customerModuleField.customFields.forEach((item) => {
    columns.value.push({
      label: item.showName,
      prop: item.fieldName,
      cellRenderer: createHighlightRender(item.fieldName)
    })
  })
  columns.value = columns.value.concat([
    {
      label: '联系人姓名',
      prop: 'contactName',
      cellRenderer: createHighlightRender('contactName')
    },
    {
      label: '联系人昵称',
      prop: 'contactNickName',
      cellRenderer: createHighlightRender('contactNickName')
    },
    { label: '主联系人职位', prop: 'contactPosition' }
  ])

  const contactModuleField = await getBussinessModule(SettingBusinessModuleEnum.CUSTOMER_CONTACT)
  contactModuleField.immutableFields.forEach((item) => {
    columns.value.push({
      label: '联系人' + item.showName,
      prop: 'contact' + upperFirst(item.fieldName),

      formatter: (row) =>
        row['contact' + upperFirst(item.fieldName)] == 0
          ? ''
          : item.options.find((obj) => obj.id === row['contact' + upperFirst(item.fieldName)])?.name
    })
  })

  columns.value = columns.value.concat([
    {
      label: '主联系人电话',
      prop: 'contactPhone',
      cellRenderer: createHighlightRender('contactPhone')
    },
    {
      label: '主联系人邮箱',
      prop: 'contactMail',
      cellRenderer: createHighlightRender('contactMail')
    },
    {
      label: '主联系人社交媒体',
      prop: 'contactSocialMedia',
      cellRenderer: createHighlightRender('contactSocialMedia')
    },
    {
      label: '主联系人地址',
      prop: 'contactAddress',
      cellRenderer: createHighlightRender('contactAddress')
    }
  ])

  contactModuleField.customFields.forEach((item) => {
    columns.value.push({
      label: '联系人' + item.showName,
      prop: 'contact' + upperFirst(item.fieldName),
      cellRenderer: createHighlightRender('contact' + upperFirst(item.fieldName))
    })
  })

  columns.value = columns.value.concat([
    {
      label: '创建时间',
      prop: 'createTime'
    },
    {
      label: '上次修改时间',
      prop: 'updateTime'
    }
  ])

  recycleMessage.value = '回收站'
  queryParams.value = {
    searchText: '',
    isMailSuffix: true
  }
}

/** 搜索按钮操作 */
const handleClickSearch = async () => {
  if (queryParams.value.searchText.length < 3) {
    message.error('搜索不能小于3个字符')
    return
  }

  await getList()
}

/** 处理响应事件  */
const getList = async () => {
  const searchText = queryParams.value.searchText
  const customerInfos = await CustomerCheckApi.duplicateSearch(queryParams.value)
  // 联系人
  let contactIndex = 0
  let phoneIndex = 0
  let mailIndex = 0
  let socialMediaIndex = 0

  customerInfos.forEach((customerInfo) => {
    // 网址
    customerInfo.showWebsite = ''
    if (settingColumnNames.value.includes('website')) {
      customerInfo.websites.forEach((websiteInfo) => {
        if (websiteInfo.website.includes(searchText)) {
          customerInfo.showWebsite =
            customerInfo.showWebsite + customerInfo.showWebsite.length > 0
              ? ','
              : '' + websiteInfo.website
        }
      })
    }

    customerInfo.contacts.forEach((contactInfo, currentContactIndex) => {
      // 联系人姓名
      if (
        settingColumnNames.value.includes('contact_name') &&
        contactInfo.name.includes(searchText)
      )
        contactIndex = currentContactIndex
      // 联系人昵称
      if (
        settingColumnNames.value.includes('contact_nick_name') &&
        contactInfo.nickName.includes(searchText)
      )
        contactIndex = currentContactIndex
      // 联系人昵称
      if (
        settingColumnNames.value.includes('contact_address') &&
        contactInfo.address.includes(searchText)
      )
        contactIndex = currentContactIndex

      if (settingColumnNames.value.includes('contact_phone')) {
        contactInfo.phones.forEach((phoneInfo, currentPhoneIndex) => {
          if (phoneInfo.phoneNo.includes(searchText)) {
            contactIndex = currentContactIndex
            phoneIndex = currentPhoneIndex
          }
        })
      }

      if (settingColumnNames.value.includes('contact_mail')) {
        contactInfo.mails.forEach((mailInfo, currentMailIndex) => {
          if (mailInfo.mailAddress.includes(searchText)) {
            contactIndex = currentContactIndex
            mailIndex = currentMailIndex
          }
        })
      }

      if (settingColumnNames.value.includes('contact_social_media')) {
        contactInfo.socialMedias.forEach((socialMediaInfo, currentSocialMediaIndex) => {
          if (socialMediaInfo.socialAccount.includes(searchText)) {
            contactIndex = currentContactIndex
            socialMediaIndex = currentSocialMediaIndex
          }
        })
      }

      // 自定义字段
      if (
        settingColumnNames.value.includes('contact_custom_field1') &&
        contactInfo.customField1.includes(searchText)
      )
        contactIndex = currentContactIndex

      if (
        settingColumnNames.value.includes('contact_custom_field2') &&
        contactInfo.customField2.includes(searchText)
      )
        contactIndex = currentContactIndex
      if (
        settingColumnNames.value.includes('contact_custom_field3') &&
        contactInfo.customField3.includes(searchText)
      )
        contactIndex = currentContactIndex
      if (
        settingColumnNames.value.includes('contact_custom_field4') &&
        contactInfo.customField4.includes(searchText)
      )
        contactIndex = currentContactIndex
      if (
        settingColumnNames.value.includes('contact_custom_field5') &&
        contactInfo.customField5.includes(searchText)
      )
        contactIndex = currentContactIndex
      if (
        settingColumnNames.value.includes('contact_custom_field6') &&
        contactInfo.customField6.includes(searchText)
      )
        contactIndex = currentContactIndex
      if (
        settingColumnNames.value.includes('contact_custom_field7') &&
        contactInfo.customField7.includes(searchText)
      )
        contactIndex = currentContactIndex
      if (
        settingColumnNames.value.includes('contact_custom_field8') &&
        contactInfo.customField8.includes(searchText)
      )
        contactIndex = currentContactIndex
      if (
        settingColumnNames.value.includes('contact_custom_field9') &&
        contactInfo.customField9.includes(searchText)
      )
        contactIndex = currentContactIndex
      if (
        settingColumnNames.value.includes('contact_custom_field10') &&
        contactInfo.customField10.includes(searchText)
      )
        contactIndex = currentContactIndex
    })

    customerInfo.contactName = customerInfo.contacts[contactIndex].name
    customerInfo.contactNickName = customerInfo.contacts[contactIndex].nickName
    customerInfo.contactAddress = customerInfo.contacts[contactIndex].address
    if (customerInfo.contacts[contactIndex].phones.length > 0)
      customerInfo.contactPhone = customerInfo.contacts[contactIndex].phones[phoneIndex].phoneNo
    else customerInfo.contactPhone = ''
    if (customerInfo.contacts[contactIndex].mails.length > 0)
      customerInfo.contactMail = customerInfo.contacts[contactIndex].mails[mailIndex].mailAddress
    else customerInfo.contactMail = ''

    if (customerInfo.contacts[contactIndex].socialMedias.length > 0)
      customerInfo.contactSocialMedia =
        socialMediaType.value.find(
          (obj) =>
            obj.value ===
            customerInfo.contacts[contactIndex].socialMedias[socialMediaIndex].socialType
        )?.label +
        ':' +
        customerInfo.contacts[contactIndex].socialMedias[socialMediaIndex].socialAccount
    else customerInfo.contactSocialMedia = ''
    customerInfo.contactCustomField1 = customerInfo.contacts[contactIndex].customField1
    customerInfo.contactCustomField2 = customerInfo.contacts[contactIndex].customField2
    customerInfo.contactCustomField3 = customerInfo.contacts[contactIndex].customField3
    customerInfo.contactCustomField4 = customerInfo.contacts[contactIndex].customField4
    customerInfo.contactCustomField5 = customerInfo.contacts[contactIndex].customField5
    customerInfo.contactCustomField6 = customerInfo.contacts[contactIndex].customField6
    customerInfo.contactCustomField7 = customerInfo.contacts[contactIndex].customField7
    customerInfo.contactCustomField8 = customerInfo.contacts[contactIndex].customField8
    customerInfo.contactCustomField9 = customerInfo.contacts[contactIndex].customField9
    customerInfo.contactCustomField10 = customerInfo.contacts[contactIndex].customField10
  })

  queryData.value = customerInfos
}

const getDuplicateSetting = async () => {
  const checkColumns = await CustomerCheckApi.settingQuery()
  settingColumnNames.value = getKeyList(checkColumns, 'columnName')
}

const handleClickMerge = () => {
  let selectRows = tableRef.value.getTableRef().getSelectionRows()
  if (selectRows.length == 0) {
    message.error('请选择要合并的客户')
    return
  }

  if (selectRows.length == 1) {
    message.error('请至少选择2个客户')
    return
  }
  if (selectRows.length > 5) {
    message.error('最多选择5个客户')
    return
  }

  mergeRef.value.open(selectRows)
}

const handleClickSetting = () => {
  settingRef.value.open()
}
</script>
